from aliyunsdkcore.client import AcsClient
from aliyunsdkgreen.request.v20180509 import TextScanRequest, ImageSyncScanRequest
import json
import base64

# 替换为你的阿里云AccessKey
ACCESS_KEY_ID = 'LTAI5tQs9yXAvthECXRUiktt'
ACCESS_KEY_SECRET = 'rKkUrtfOUfCfn4iUhfVptiJB2SITFJ'
REGION = 'cn-shanghai'

client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET, REGION)

def check_text(text):
    """阿里云文本内容安全检测，返回suggestion"""
    request = TextScanRequest.TextScanRequest()
    request.set_accept_format('JSON')
    request.set_content(json.dumps({
        "scenes": ["antispam"],
        "tasks": [{"content": text}]
    }))
    response = client.do_action_with_exception(request)
    result = json.loads(response)
    try:
        suggestion = result['data'][0]['results'][0]['suggestion']
        return suggestion  # 'pass'/'block'/'review'
    except Exception:
        return 'block'  # 检测失败时默认拦截

def check_image(url):
    """阿里云图片内容安全检测，只拦截涉黄、涉政、暴力，其他一律放行"""
    request = ImageSyncScanRequest.ImageSyncScanRequest()
    request.set_accept_format('JSON')
    request.set_content(json.dumps({
        "scenes": ["porn", "terrorism", "ad", "live", "logo", "qrcode"],
        "tasks": [{"dataId": "img1", "url": url}]
    }))
    try:
        response = client.do_action_with_exception(request)
        result = json.loads(response)
        results = result['data'][0]['results']
        for r in results:
            label = r.get('label', '')
            suggestion = r.get('suggestion', '')
            if label in ('porn', 'terrorism', 'bloody') and suggestion == 'block':
                print(f"图片被拦截: label={label}, suggestion={suggestion}, url={url}")
                return True
        return False
    except Exception as e:
        print(f"图片审核异常: {e}, url={url}")
        return False
